package com.bestcem.xm.award.controller;

import com.bestcem.xm.award.constant.Constants;
import com.bestcem.xm.award.service.impl.RedPacketAwardServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信红红包重定向
 *
 * @author jie.yao <jie.yao@idiaoyan.com>
 * @version v1.0
 * @date 2021/9/8 17:45
 */
@Slf4j
@RestController
@RequestMapping(value = "/award", produces = MediaType.APPLICATION_JSON_VALUE)
public class WxRedirectController {

    /**
     * 由于私有部署项目域名不同，导致微信回调报错，saas提供通用重定向接口，再跳转到私有部署项目
     * 路径{@link RedPacketAwardServiceImpl} genPickUrl方法,redirectUrl
     *
     * @param request      请求
     * @param response     响应
     * @param surveyId     问卷id
     * @param customDomain 域名
     * @author jie.yao <jie.yao@idiaoyan.com>
     * @date 2018/8/19 22:26
     */
    @GetMapping("/bonus/saas/wx_redirect/{surveyId}")
    public void wxSaasRedirect(HttpServletRequest request, HttpServletResponse response,
                               @PathVariable(value = "surveyId") String surveyId,
                               @RequestParam(value = "custom_domain", required = false) String customDomain) {
        if (StringUtils.isBlank(customDomain)) {
            customDomain = Constants.BLANK;
        }
        String redirectUrl = String.format("%s/s/%s/award/bonus?%s", customDomain, surveyId, request.getQueryString());
        if (log.isInfoEnabled()) {
            log.info("[Award] 微信红包重定向url:{}", redirectUrl);
        }
        try {
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            log.error("[Award] 微信重定向失败 redirectUrl:{}", redirectUrl, e);
        }
    }
}
